<template>
    <div class="sku">
        <el-page-header title="返回商品列表" content="新增商品" @back="$router.back()"></el-page-header>
        <el-form style="margin-top:20px" :model="formData" :rules="formRules" label-width="auto">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="基本信息" name="1">
                    <el-row type="flex" :gutter="10" style="margin-top:30px">
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品名称" prop="goods_name">
                                <el-input v-model="formData.goods_name" clearable placeholder="请输入商品名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品图片" prop="imagesIds">
                                <el-upload-image v-model="formData.imagesIds" :limit="5"></el-upload-image>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品分类" prop="categoryIds">
                                <el-select v-model="formData.categoryIds" placeholder="请选择">
                                    <el-option v-for="(item, index) in goodsTypeData" :key="index" :label="item.name"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品属性" prop="goods_source">
                                <el-select v-model="formData.goods_source" placeholder="请选择">
                                    <el-option v-for="(item, index) in sourcelist" :key="item.id" :label="item.title"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="20" :offset="2">
						   <el-form-item label="赠送积分比例(%)" prop="score_rate">
						        <el-input
						            v-model="formData.score_rate"
						            clearable
									type="number"
						            placeholder="100% 填100，1.5% 填1.5 ，0为不赠送"
						        ></el-input>
						    </el-form-item>
						</el-col> -->
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品状态" prop="status">
                                <el-radio-group v-model="formData.status">
                                    <el-radio :label="10">上架</el-radio>
                                    <el-radio :label="20">下架</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="20" :offset="2">
                            <el-form-item
                                label="会员折扣"
                                prop="is_enable_grade"
                            >
                                <el-radio-group
                                    v-model="formData.is_enable_grade"
                                >
                                    <el-radio :label="1">开启</el-radio>
                                    <el-radio :label="0">关闭</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col> -->
                        <!-- is_special 是否特价商品0否 1是 -->
                        <!-- <el-col :span="20" :offset="2">
						    <el-form-item
						        label="是否是特价商品"
						        prop="is_special"
						    >
						        <el-radio-group
						            v-model="formData.is_special"
						        >
						            <el-radio :label="1">是</el-radio>
						            <el-radio :label="0">否 </el-radio>
						        </el-radio-group>
						    </el-form-item>
						</el-col> -->
                        <el-col :span="20" :offset="2">
                            <el-form-item label="是否可使用积分抵扣" prop="is_dk">
                                <el-radio-group v-model="formData.is_dk" :disabled="$store.getters.isAdmin == false">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否 </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="是否赠送积分" prop="is_points_gift">
                                <el-radio-group v-model="formData.is_points_gift">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否 </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2" v-if="formData.is_points_gift == 1">
                            <el-form-item label="赠送积分数量" prop="gift_score">
                                <el-input-number v-model="formData.gift_score" :controls="false"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="是否是积分商品" prop="is_points_discount">
                                <el-radio-group v-model="formData.is_points_discount">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否 </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="是否是热门推荐商品" prop="is_special">
                                <el-radio-group v-model="formData.is_special">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否 </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="是否是严选商品" prop="is_yx">
                                <el-radio-group v-model="formData.is_yx">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否 </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="规格/库存" name="2">
                    <el-row :gutter="10" style="margin-top:30px">
                        <el-col :span="20" :offset="2">
                            <el-form-item label="规格类型" prop="spec_type">
                                <el-radio-group v-model="formData.spec_type">
                                    <el-radio :label="10">单规格</el-radio>
                                    <el-radio :label="20">多规格</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <template v-if="formData.spec_type === 10">
                            <el-col :span="20" :offset="2">
                                <el-form-item label="商品价格" prop="goods_price">
                                    <el-input v-model="formData.goods_price" placeholder="请输入">
                                        <template slot="append">元</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="20" :offset="2">
                                <el-form-item label="进货价" prop="line_price">
                                    <el-input v-model="formData.line_price" placeholder="请输入">
                                        <template slot="append">元</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="20" :offset="2">
							    <el-form-item label="代理价" prop="agent_price">
							        <el-input
							            v-model="formData.agent_price"
							            placeholder="请输入"
							        >
							            <template slot="append">元</template>
							        </el-input>
							    </el-form-item>
							</el-col> -->
                            <el-col :span="20" :offset="2">
                                <el-form-item label="商品重量" prop="goods_weight">
                                    <el-input v-model="formData.goods_weight" placeholder="请输入"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="20" :offset="2">
                                <el-form-item label="库存量" prop="stock_num">
                                    <el-input v-model="formData.stock_num" placeholder="请输入"></el-input>
                                </el-form-item>
                            </el-col>
                        </template>
                        <template v-else>
                            <el-col :span="20" :offset="2">
                                <div class="sku_container">
                                    <div class="sku_group mb10" v-for="(spec, index) in specification" :key="spec.id">
                                        <div class="spec_title">
                                            <span class="label">规格名：</span>
                                            <el-input class="input" placeholder="请输入规格名"
                                                v-model.trim="spec.value"></el-input><span class="remove"
                                                @click="delSepc(index)">×</span>
                                        </div>
                                        <div class="group_container">
                                            <span class="label">规格值：</span>
                                            <el-popover placement="bottom" width="120" trigger="click" v-for="(option,
                                                option_index) in spec.leaf" :key="option_index">
                                                <el-input v-model.trim="option.value"
                                                    :style="{ width: '110px' }"></el-input>
                                                <div class="sku_item" slot="reference">
                                                    <span class="remove" @click.stop="
                                                        delOption(
                                                            index,
                                                            option_index
                                                        )
                                                        ">×</span>
                                                    <div class="text">
                                                        {{ option.value }}
                                                    </div>
                                                </div>
                                            </el-popover>
                                            <el-input class="input" suffix-icon="el-icon-plus" v-model="addValues[index]"
                                                placeholder="多个产品属性以空格隔开" @keyup.native.enter="
                                                    addOption(index)
                                                    " @blur="addOption(index)"></el-input>
                                        </div>
                                    </div>
                                    <div class="spec_title">
                                        <el-button type="primary" icon="el-icon-plus" :disabled="disabled"
                                            @click="addSpec">添加规格项目</el-button>
                                    </div>
                                </div>
                                <div class="sku_container" v-if="false">
                                    <SkuSelect :skusData="specificationFilter"></SkuSelect>
                                </div>
                                <div class="sku_container">
                                    <SkuTable ref="skuTable" :skusData="specificationFilter"></SkuTable>
                                </div>
                            </el-col>
                        </template>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="商品详情" name="3">
                    <el-row :gutter="10">
                        <el-col :span="20" :offset="2">
                            <div>
                                <!-- <Toolbar style="border-bottom: 1px solid #ccc,width:375px" :editor="editor"
                                    :defaultConfig="toolbarConfig" :mode="mode" /> -->
                                <Editor height="700px" style="width:375px" v-model="formData.content"
                                    :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
                            </div>
                        </el-col>
                    </el-row>
                </el-tab-pane>
            </el-tabs>
        </el-form>
        <el-row :gutter="10" style="margin-top:20px;">
            <el-col :span="20" :offset="2">
                <el-button @click="submit" type="primary">提交</el-button>
            </el-col>
        </el-row>
    </div>
</template>

<script>
/* @eslint-disabled */
import SkuSelect from "@/components/sku-select";
import SkuTable from "@/components/sku-table";
import { createUniqueString, uniqueArr } from "@/utils";
import ElUploadImage from "@/components/el-upload-image.vue";
// import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { post, get } from "@/assets/js/http.js";
import Editor from '@/components/editor.vue'

export default {
    name: "view-sku",
    components: {
        SkuSelect,
        SkuTable,
        ElUploadImage,
        Editor,
        // Toolbar
    },
    data() {
        return {
            goodsTypeData: [],
            editor: null,
            toolbarConfig: {},
            editorConfig: {
                MENU_CONF: {
                    uploadImage: {
                        fieldName: "file",
                        server: "/admin/ajax/upload",
                        headers: {
                            batoken: this.$store.state.token
                        },
                        customInsert(res, insertFn) {
                            insertFn($store.getters.baseUrl + res.data.file.url);
                        }
                    },
                    uploadVideo: {
                        fieldName: "file",
                        server: "/admin/ajax/upload",
                        headers: {
                            batoken: this.$store.state.token,
                        },
                        /* eslint-disable-next-line */
                        customInsert(res, insertFn) {
                            insertFn($store.getters.baseUrl + res.data.file.url)
                        },
                    },
                }
            },
            mode: "default",
            activeTab: "1",
            addValues: [],
            specification: [],
            formData: {
                goods_name: "",
                categoryIds: [],
                goods_source: '',
                source_name: '',
                // score_rate:0,//100% 填100，1.5% 填1.5 ，0为不赠送
                goods_price: "",
                line_price: "",
                agent_price: '',
                imagesIds: [],
                serviceIds: [],
                goods_weight: "",
                spec_type: 10,
                status: 10,
                is_enable_grade: 1,
                is_alone_grade: 0,
                is_points_discount: 0,
                is_special: 0,
                is_points_gift: 0,
                stock_num: "0",
                content: "",
                is_yx: 0,
                is_dk:0
            },
            formRules: {
                gift_score: [
                    { required: true, message: '请输入赠送积分数量', trigger: 'blur' },
                    { type: 'number', message: '请输入数字', trigger: 'blur' },
                ]
            },
            sourcelist: [{ title: '自有商品', id: 1 }, { title: '寄卖商品', id: 2 }],//商品属性 1自有商品 2寄卖商品
        };
    },
    mounted() {
        this.getGoodsTypeData();
    },
    computed: {
        disabled() {
            return (
                this.specification.length > 3 ||
                this.specification.some(item => !item.value)
            );
        },
        // 过滤掉属性名和属性值为空的数据规格项目
        specificationFilter() {
            return this.specification.filter(
                item => item.value && item.leaf.length
            );
        }
    },
    methods: {
        async getGoodsTypeData() {
            const data = await get({
                url: "/admin/shop.GoodsCategory/index",
                loading: true,
                params: {
                    page: 1,
                    limit: 999
                }
            });
            this.goodsTypeData = data.list;
        },
        onCreated(editor) {
            this.editor = Object.seal(editor);
        },
        addSpec() {
            this.specification.push({
                id: createUniqueString() + "_id",
                value: "",
                leaf: []
            });
        },
        delSepc(index) {
            this.specification.splice(index, 1);
        },
        addOption(index) {
            let str = this.addValues[index] || "";
            str = str.trim();
            if (!str) return;
            const oldArr = this.specification[index].leaf;
            const arr = str
                .split(/\s+/) // 使用空格分割成数组
                .filter(value => !oldArr.some(option => option.value === value)) // 过滤掉 oldArr 已存在的 value
                .map(value => ({ id: createUniqueString() + "_id", value })); // 把 value 转成对象，id 设置为 null
            this.specification[index].leaf = uniqueArr([...oldArr, ...arr]);
            this.$set(this.addValues, index, "");
        },
        delOption(spec_index, option_index) {
            this.specification[spec_index].leaf.splice(option_index, 1);
        },
        async submit() {
            try {
                this.$loading()
                const formData = JSON.parse(JSON.stringify(this.formData));
                console.log(formData, 'formData')
                if (formData.spec_type == 20) {
                    const specList = [];
                    this.specificationFilter.forEach(item => {
                        const specItem = {};
                        specItem.key = item.id;
                        specItem.spec_name = item.value;
                        specItem.valueList = [];
                        item.leaf.forEach(sitem => {
                            specItem.valueList.push({
                                key: sitem.id,
                                groupKey: item.value,
                                spec_value: sitem.value
                            });
                        });
                        specList.push(specItem);
                    });
                    console.log(this.specificationFilter, 'this.specificationFilter')
                    const skuData = this.$refs.skuTable.getData();
                    const skuList = [];

                    skuData.forEach(item => {
                        const skuItem = {
                            goods_price: item.goods_price,
                            goods_sku_no: item.goods_sku_no,
                            goods_weight: item.goods_weight,
                            image_id: item.image
                                ? item.image[0].id
                                : 0,
                            line_price: item.line_price,
                            stock_num: item.stock_num,
                            agent_price: item.agent_price,
                            skuKeys: []
                        };
                        item.skus.forEach((sitem, sindex) => {
                            const pindex = specList.findIndex(
                                ssitem => ssitem.spec_name === sitem.k
                            );
                            const cindex = specList[pindex].valueList.findIndex(
                                ssitem => ssitem.spec_value === sitem.v
                            );
                            skuItem.skuKeys.push({
                                groupKey: pindex,
                                valueKey: cindex
                            });
                            skuItem["spec_value_" + sindex] = sitem.v;
                        });
                        skuList.push(skuItem);
                    });
                    console.log(skuData, 'skuData')
                    formData.specData = {
                        skuList: skuList,
                        specList: specList
                    };
                    console.log(formData.specData, 'formData.specData,data')
                }
                formData.imagesIds = formData.imagesIds.map(item => {
                    return item.id;
                });
                formData.categoryIds = [formData.categoryIds]
                console.log(formData.imagesIds, 'formData.imagesIds')
                await post({
                    url: "/admin/shop.goods/add",
                    data: formData,
                    loading: true,
                    successTip: true
                });
                this.$emit("update");
                this.$router.back();
            } finally {
                this.$loading().close()
            }

        }
    },
    beforeDestroy() {
        const editor = this.editor;
        if (editor == null) return;
        editor.destroy();
    }
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>

<style scoped>
.sku {
    margin: 15px;
}

.sku_container {
    width: 100%;
    font-size: 12px;
    color: #666;
    padding: 10px;
    border: 1px solid #e5e5e5;
    margin-bottom: 15px;
}

.remove {
    display: none;
    position: absolute;
    z-index: 2;
    width: 18px;
    height: 18px;
    font-size: 14px;
    line-height: 16px;
    color: #fff;
    text-align: center;
    cursor: pointer;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
}

.sku_group {
    margin-bottom: 10px;
}

.sku_group:hover .spec_title .remove {
    display: block;
}

.spec_title {
    position: relative;
    padding: 7px 10px;
    background-color: #f8f8f8;
    line-height: 16px;
    font-weight: 400;
}

.spec_title .input {
    width: 200px;
}

.spec_title .remove {
    top: 12px;
    right: 10px;
}

.group_container {
    padding: 10px 10px 0;
}

.group_container .input {
    width: 250px;
}

.group_container .sku_item {
    background-color: #f8f8f8;
    padding: 10px;
    display: inline-block;
    margin-right: 10px;
    vertical-align: middle;
    text-align: center;
    position: relative;
    border-radius: 2px;
    cursor: pointer;
}

.group_container .sku_item:hover .remove {
    display: block;
}

.group_container .sku_item .remove {
    top: -8px;
    right: -8px;
}

.group_container .sku_item .text {
    display: block;
    width: 74px;
    margin: 0 auto;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>